﻿using Audit.Core;
using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using ExpressionToWhere;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class Sys_UserBusiness : BaseRepository<Sys_User>, ISys_UserBusiness
    {
        public Sys_UserBusiness()
        {

        }

        public Sys_UserBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public bool IsExist(string code)
        {
            try
            {
                if (string.IsNullOrEmpty(code)) return true;
                Expression<Func<Sys_User, bool>> exp = user => user.Code == code;
                List<Sys_User> list = base.GetList(exp, false).ToList();
                if (list != null && list.Count > 0) return true;
                return false;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "检查系统用户是否存在失败", "code=" + code, ex, "DapperCore");
                return false;
            }
        }

        public bool Add(Sys_User user)
        {
            using (AuditScope scope = AuditScope.Create("Sys_User:Add", () => user))
            {
                try
                {
                    scope.Comment("添加单个系统用户角色");
                    scope.SetCustomField("Module", "Sys_User");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Insert);
                    bool success = base.Add(user);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统用户添加失败", "role=" + JsonConvert.SerializeObject(user), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool UpdateNotNull(Sys_User user)
        {
            Sys_User old = base.Get(user.Id);
            using (AuditScope scope = AuditScope.Create("Sys_User:Edit", () => old))
            {
                try
                {
                    scope.Comment("编辑单个系统用户");
                    scope.SetCustomField("Module", "Sys_User");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Update);
                    old = user;
                    bool success = base.UpdateNotNull(user);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统用户修改失败", "menu=" + JsonConvert.SerializeObject(user), ex, "DapperCore");
                    return false;
                }
            }
        }

        public BasicUserInfo GetBasicUserInfo(string user)
        {
            try
            {
                Expression<Func<Sys_User, bool>> exp = a => a.Code == user;
                BaseRepository<Sys_User> baseRepository = new BaseRepository<Sys_User>();
                List<Sys_User> userList = baseRepository.GetList(exp).ToList();
                BasicUserInfo basicUserInfo = new BasicUserInfo()
                {
                    UserId = userList[0].Id,
                    UserCode = user,
                    UserName = userList[0].Name,
                    PinyinCode = userList[0].Name,
                    Email = userList[0].Email,
                    FirstDeptCode = "330000",
                    FirstDeptName = "信息技术部",
                    SecondDeptCode = "330300",
                    SecondDeptName = "技术解决方案部",
                    ThirdDeptCode = "330301",
                    ThirdDeptName = "IT平台部"
                };
                return basicUserInfo;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取BasicUserInfo失败", "user=" + user, ex, "DapperCore");
                return new BasicUserInfo();
            }
        }

        public (List<Sys_User> users, int count) GetPageList(int pageIndex, int rowsPerPage, string search, string orderby)
        {
            try
            {
                if (pageIndex < 0 || rowsPerPage < 1)
                {
                    return (new List<Sys_User>(), 0);
                }
                Expression<Func<Sys_User, bool>> exp = user => user.IsDeleted == 0 && (user.Name.Contains(search) || user.Code.Contains(search));
                List<Sys_User> roles = base.GetPagelist(pageIndex + 1, rowsPerPage, exp, orderby).ToList();
                int count = base.GetListCount(exp);
                NlogUtility.WriteInfo(MethodBase.GetCurrentMethod().DeclaringType.FullName, "查询用户分页信息", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，search=" + search + "，orderby=" + orderby, "DapperCore");
                return (roles, count);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取用户分页信息失败", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，search=" + search, ex, "DapperCore");
                return (new List<Sys_User>(), 0);
            }
        }

        public bool Delete(string ids, string deleter)
        {
            using (AuditScope scope = AuditScope.Create("Sys_User:Delete", () => ids))
            {
                try
                {
                    if (string.IsNullOrEmpty(ids)) return true;
                    List<string> idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (idList.Count < 1) return true;
                    scope.Comment("软删除系统用户");
                    scope.SetCustomField("Module", "Sys_User");
                    scope.SetCustomField("Operator", deleter);
                    scope.SetCustomField("Operation", Operation.Delete);
                    //定义时间变量，保证同一次删除数据的删除时间相等
                    DateTime dateTime = DateTime.Now;
                    Expression<Func<Sys_User, bool>> exp = user => user.Id.In(idList);
                    bool success = base.SoftDelete(exp, deleter, dateTime);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统用户软删除失败", "ids=" + ids, ex, "DapperCore");
                    return false;
                }
            }
        }
    }
}